/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {  Button, Form, Input,Table, message } from "antd";
import styles from './friendship.module.less'
import {  useEffect, useMemo, useState } from "react";
import { ColumnsType } from "antd/es/table";
import { useForm } from "antd/es/form/Form";
import { createOneToOne, findChatroom, friendshipList } from "../../interfaces";
import { AddFriendModal } from "./addFriendModal";
import { getUserInfo } from "../chat";
import { useNavigate } from "react-router-dom";

function Friendship() {

  const [friendshipResult, setFriendshipResult] = useState<Array<FriendshipSearchResult>>([])
  const [isAddFriendModalOpen, setAddFriendModalOpen] = useState(false);


  const navigate = useNavigate();

  async function goToChat(friendId:number){
    const userId = getUserInfo().id
    try{
      const res = await findChatroom(userId,friendId);
      if(res.data){
        navigate('/chat',{
          state:{
            chatroomId: res.data
          }
        });
      } else {
        const res2 = await createOneToOne(friendId);
        navigate('/chat',{
          state:{
            chatrooomId: res2.data
          }
        })
      }

    }catch(e:any){
      message.error(e.response?.data?.message || '请求失败')
    }
}



  //表格
  const columns: ColumnsType<FriendshipSearchResult> = useMemo(() => [
    {
      title:'ID',
      dataIndex:'id'
    },
    {
      title:'用户名',
      dataIndex:'username',
    },
    {
      title: '昵称',
      dataIndex: 'nickName'  //这里大写写成小写，所以没有显示昵称
    },
    {
      title: '头像',
      dataIndex: 'headPic',
      //接收当前索引和当前数据对象
      render: (_, record) => (
        <div>
          <img src={record.headPic} />
        </div>
      )
    },
    {
      title: '邮箱',
      dataIndex: 'email'
    },
    {
      title: '操作',
      render: (_, record) => (
        <div>
          <a href="#" onClick={() => goToChat(record.id)}>聊天</a>
        </div>
      )
    }
  ], [])

 
  //
  const searchFriend = async (values: SearchFriend) => {
    try {
      const res = await friendshipList(values.name || '')
      if (res.status === 200 || res.status === 201) {
        setFriendshipResult(res.data.map((item: FriendshipSearchResult) => {
          return {
           ...item,
            key: item.id
          }
        }
        ))
      }

    } catch (e: any) {
      message.error(e.response?.data?.message || '请求失败')
    }
  }

  const [from] = useForm()

  useEffect(() => {
    searchFriend({
      name: from.getFieldValue('name')
    })
  }, [])


  return (
    <div id={styles.container}>
      <div className={styles.friendship_form}>
        <Form
          form={from}
          onFinish={searchFriend}
          name="search"
          layout="inline"
          colon={false}
        >
          <Form.Item label='名称' name='name'>
            {/* 没有绑定name导致搜不出来。。 */}
            <Input />
          </Form.Item>

          <Form.Item label=' '>
            <Button type="primary" htmlType="submit" className={styles.btn}>
              搜索
            </Button>
          </Form.Item>
          <Form.Item label=''>
             <Button type="primary"  className={styles.btn}  onClick={() => setAddFriendModalOpen(true) }>
              添加好友
             </Button>
          </Form.Item>
        </Form>
      </div>
      <div className={styles.friendship_table}>
        <Table columns={columns} dataSource={friendshipResult} />
      </div>
      <AddFriendModal isOpen={isAddFriendModalOpen} handleClose={() =>{
         setAddFriendModalOpen(false)
      }} />
    </div>
  )
}

export default Friendship











/**
 * 8.15
 * columns中nickName写成了nickname，导致没有显示昵称
 * 服务端
 */